<template>
  <div class="customer-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>客户管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleAdd">新增客户</el-button>
            <el-upload
              action=""
              :http-request="handleImport"
              :show-file-list="false"
              accept=".xlsx,.xls"
              style="display: inline-block; margin: 0 10px"
            >
              <el-button>导入客户</el-button>
            </el-upload>
            <el-button @click="handleExport">导出客户</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="客户名称">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户名称" clearable />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item label="客户状态">
          <el-select v-model="searchForm.customerStatus" placeholder="请选择客户状态" clearable>
            <el-option label="潜在客户" value="potential" />
            <el-option label="意向客户" value="intention" />
            <el-option label="成交客户" value="deal" />
            <el-option label="失效客户" value="invalid" />
          </el-select>
        </el-form-item>
        <el-form-item label="意向等级">
          <el-select v-model="searchForm.intentionLevel" placeholder="请选择意向等级" clearable>
            <el-option label="A级" value="A" />
            <el-option label="B级" value="B" />
            <el-option label="C级" value="C" />
            <el-option label="D级" value="D" />
          </el-select>
        </el-form-item>
        <el-form-item label="来源渠道">
          <el-select v-model="searchForm.channelId" placeholder="请选择来源渠道" clearable filterable>
            <el-option
              v-for="channel in channelOptions"
              :key="channel.id"
              :label="channel.channelName"
              :value="channel.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分配状态">
          <el-select v-model="searchForm.allocationStatus" placeholder="请选择分配状态" clearable>
            <el-option label="未分配" value="unallocated" />
            <el-option label="已分配" value="allocated" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 批量操作 -->
      <div class="batch-actions" v-if="selectedRows.length > 0">
        <el-button type="primary" @click="handleBatchAllocate">批量分配</el-button>
        <el-button type="warning" @click="handleBatchTransfer">批量转移</el-button>
        <el-button type="danger" @click="handleBatchInvalid">批量失效</el-button>
        <el-button @click="handleBatchDelete">批量删除</el-button>
        <el-button type="success" @click="handleExport">导出数据</el-button>
        <span class="selected-count">已选择 {{ selectedRows.length }} 条记录</span>
      </div>

      <!-- 客户表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="customerName" label="客户名称" min-width="120" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="status" label="客户状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="intentionLevel" label="意向等级" width="80">
          <template #default="{ row }">
            <el-tag :type="getIntentionLevelType(row.intentionLevel)">
              {{ getIntentionLevelLabel(row.intentionLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="channelName" label="来源渠道" width="120" />
        <el-table-column prop="allocationStatus" label="分配状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.allocationStatus === 'allocated' ? 'success' : 'warning'">
              {{ row.allocationStatus === 'allocated' ? '已分配' : '未分配' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ownerUserName" label="负责人" width="100" />
        <el-table-column prop="lastFollowUpTime" label="最后跟进时间" width="160" />
        <el-table-column prop="createdTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="handleView(row)">查看</el-button>
            <el-button type="text" @click="handleEdit(row)">编辑</el-button>
            <el-button type="text" @click="handleFollowUp(row)">跟进</el-button>
            <el-button type="text" @click="handleAllocate(row)">分配</el-button>
            <el-dropdown @command="(command) => handleMoreAction(command, row)" trigger="click">
              <el-button type="text" style="margin-left: 10px">
                更多
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="transfer">转移</el-dropdown-item>
                  <el-dropdown-item command="invalid" :disabled="row.customerStatus === 'invalid'">
                    标记失效
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination responsive-pagination"
      />
    </el-card>

    <!-- 客户详情对话框 -->
    <el-dialog
      v-model="detailDialog.visible"
      title="客户详情"
      width="800px"
      class="responsive-dialog"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="客户姓名">{{ detailDialog.data.customerName }}</el-descriptions-item>
        <el-descriptions-item label="手机号码">{{ detailDialog.data.phone }}</el-descriptions-item>
        <el-descriptions-item label="客户状态">
          <el-tag :type="getCustomerStatusType(detailDialog.data.customerStatus)">
            {{ getCustomerStatusLabel(detailDialog.data.customerStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="意向等级">
          <el-tag :type="getIntentionLevelType(detailDialog.data.intentionLevel)">
            {{ getIntentionLevelLabel(detailDialog.data.intentionLevel) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="客户来源">
          {{ getCustomerSourceLabel(detailDialog.data.customerSource) }}
        </el-descriptions-item>
        <el-descriptions-item label="所属渠道">{{ detailDialog.data.channelName }}</el-descriptions-item>
        <el-descriptions-item label="所属用户">{{ detailDialog.data.userName }}</el-descriptions-item>
        <el-descriptions-item label="分配状态">
          <el-tag :type="detailDialog.data.allocationStatus === 'allocated' ? 'success' : 'warning'">
            {{ detailDialog.data.allocationStatus === 'allocated' ? '已分配' : '未分配' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="贷款金额">
          <span v-if="detailDialog.data.loanAmount">{{ formatCurrency(detailDialog.data.loanAmount) }}</span>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="跟进次数">{{ detailDialog.data.followUpCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="最后跟进">{{ detailDialog.data.lastFollowUpTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="下次跟进">{{ detailDialog.data.nextFollowUpTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailDialog.data.remark || '无' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailDialog.data.createdTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailDialog.data.updatedTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 新增/编辑客户对话框 -->
    <el-dialog
      v-model="formDialog.visible"
      :title="formDialog.title"
      width="600px"
      class="responsive-dialog"
    >
      <el-form ref="customerFormRef" :model="formDialog.form" :rules="formRules" label-width="100px">
        <el-form-item label="客户姓名" prop="customerName">
          <el-input v-model="formDialog.form.customerName" placeholder="请输入客户姓名" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="formDialog.form.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="客户状态" prop="customerStatus">
          <el-select v-model="formDialog.form.customerStatus" placeholder="请选择客户状态" style="width: 100%">
            <el-option label="潜在客户" value="potential" />
            <el-option label="意向客户" value="intention" />
            <el-option label="成交客户" value="deal" />
            <el-option label="失效客户" value="invalid" />
          </el-select>
        </el-form-item>
        <el-form-item label="意向等级" prop="intentionLevel">
          <el-select v-model="formDialog.form.intentionLevel" placeholder="请选择意向等级" style="width: 100%">
            <el-option label="A级 - 高意向" value="A" />
            <el-option label="B级 - 中意向" value="B" />
            <el-option label="C级 - 低意向" value="C" />
            <el-option label="D级 - 无意向" value="D" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户来源" prop="customerSource">
          <el-select v-model="formDialog.form.customerSource" placeholder="请选择客户来源" style="width: 100%">
            <el-option label="线上推广" value="online" />
            <el-option label="线下推广" value="offline" />
            <el-option label="转介绍" value="referral" />
            <el-option label="自然流量" value="organic" />
          </el-select>
        </el-form-item>
        <el-form-item label="贷款金额" prop="loanAmount">
          <el-input-number v-model="formDialog.form.loanAmount" :min="0" :precision="2" placeholder="请输入贷款金额" style="width: 100%" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formDialog.form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="formDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 分配客户对话框 -->
    <el-dialog
      v-model="allocateDialog.visible"
      title="分配客户"
      width="500px"
      class="responsive-dialog"
    >
      <el-form ref="allocateFormRef" :model="allocateDialog.form" :rules="allocateRules" label-width="100px">
        <el-form-item label="目标用户" prop="userId">
          <el-select v-model="allocateDialog.form.userId" placeholder="请选择目标用户" style="width: 100%">
            <el-option v-for="user in userOptions" :key="user.id" :label="user.name" :value="user.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="分配说明" prop="remark">
          <el-input v-model="allocateDialog.form.remark" type="textarea" :rows="3" placeholder="请输入分配说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="allocateDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleAllocateSubmit" :loading="allocateLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 批量分配对话框 -->
    <el-dialog
      v-model="batchAllocateDialog.visible"
      title="批量分配客户"
      width="500px"
      class="responsive-dialog"
    >
      <el-form ref="batchAllocateFormRef" :model="batchAllocateDialog.form" :rules="batchAllocateRules" label-width="100px">
        <el-form-item label="目标用户" prop="userId">
          <el-select v-model="batchAllocateDialog.form.userId" placeholder="请选择目标用户" style="width: 100%">
            <el-option v-for="user in userOptions" :key="user.id" :label="user.name" :value="user.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="分配说明" prop="remark">
          <el-input v-model="batchAllocateDialog.form.remark" type="textarea" :rows="3" placeholder="请输入分配说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchAllocateDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleBatchAllocateSubmit" :loading="batchAllocateLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 转移客户对话框 -->
    <el-dialog
      v-model="transferDialog.visible"
      title="转移客户"
      width="500px"
      class="responsive-dialog"
    >
      <el-form ref="transferFormRef" :model="transferDialog.form" :rules="transferRules" label-width="100px">
        <el-form-item label="目标用户" prop="userId">
          <el-select v-model="transferDialog.form.userId" placeholder="请选择目标用户" style="width: 100%">
            <el-option v-for="user in userOptions" :key="user.id" :label="user.name" :value="user.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="转移说明" prop="remark">
          <el-input v-model="transferDialog.form.remark" type="textarea" :rows="3" placeholder="请输入转移说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="transferDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleTransferSubmit" :loading="transferLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 批量转移对话框 -->
    <el-dialog
      v-model="batchTransferDialog.visible"
      title="批量转移客户"
      width="500px"
      class="responsive-dialog"
    >
      <el-form ref="batchTransferFormRef" :model="batchTransferDialog.form" :rules="batchTransferRules" label-width="100px">
        <el-form-item label="目标用户" prop="userId">
          <el-select v-model="batchTransferDialog.form.userId" placeholder="请选择目标用户" style="width: 100%">
            <el-option v-for="user in userOptions" :key="user.id" :label="user.name" :value="user.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="转移说明" prop="remark">
          <el-input v-model="batchTransferDialog.form.remark" type="textarea" :rows="3" placeholder="请输入转移说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchTransferDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleBatchTransferSubmit" :loading="batchTransferLoading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 导出配置对话框 -->
    <el-dialog
      v-model="exportDialog.visible"
      title="导出客户数据"
      width="600px"
      class="responsive-dialog"
    >
      <el-form label-width="100px">
        <el-form-item label="导出字段">
          <el-checkbox v-model="exportDialog.selectAll" @change="handleSelectAllFields">
            全选
          </el-checkbox>
          <el-checkbox-group v-model="exportDialog.selectedFields" style="margin-top: 10px">
            <el-row :gutter="20">
              <el-col :span="8" v-for="field in exportDialog.availableFields" :key="field.key">
                <el-checkbox :label="field.key">{{ field.label }}</el-checkbox>
              </el-col>
            </el-row>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="筛选条件">
          <el-tag
            v-for="(value, key) in exportDialog.filters"
            :key="key"
            closable
            @close="removeFilter(key)"
            style="margin-right: 10px; margin-bottom: 5px"
          >
            {{ getFilterLabel(key, value) }}
          </el-tag>
          <el-button type="text" @click="showFilterDialog = true" size="small">
            添加筛选条件
          </el-button>
        </el-form-item>
        <el-form-item label="导出格式">
          <el-radio-group v-model="exportDialog.format">
            <el-radio label="excel">Excel</el-radio>
            <el-radio label="csv">CSV</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="exportDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleExportSubmit" :loading="exportLoading">
          导出
        </el-button>
      </template>
    </el-dialog>

    <!-- 筛选条件对话框 -->
    <el-dialog
      v-model="showFilterDialog"
      title="添加筛选条件"
      width="500px"
      class="responsive-dialog"
    >
      <el-form :model="filterForm" label-width="100px">
        <el-form-item label="筛选字段">
          <el-select v-model="filterForm.field" placeholder="请选择筛选字段" style="width: 100%">
            <el-option label="客户名称" value="customerName" />
            <el-option label="手机号" value="phone" />
            <el-option label="客户状态" value="customerStatus" />
            <el-option label="意向等级" value="intentionLevel" />
            <el-option label="来源渠道" value="channelId" />
            <el-option label="分配状态" value="allocationStatus" />
            <el-option label="负责人" value="userId" />
            <el-option label="创建时间" value="createdTime" />
          </el-select>
        </el-form-item>
        <el-form-item label="筛选条件" v-if="filterForm.field">
          <el-input
            v-if="['customerName', 'phone'].includes(filterForm.field)"
            v-model="filterForm.value"
            placeholder="请输入筛选值"
          />
          <el-select
            v-else-if="filterForm.field === 'customerStatus'"
            v-model="filterForm.value"
            placeholder="请选择客户状态"
            style="width: 100%"
          >
            <el-option label="潜在客户" value="potential" />
            <el-option label="意向客户" value="intention" />
            <el-option label="成交客户" value="deal" />
            <el-option label="失效客户" value="invalid" />
          </el-select>
          <el-select
            v-else-if="filterForm.field === 'intentionLevel'"
            v-model="filterForm.value"
            placeholder="请选择意向等级"
            style="width: 100%"
          >
            <el-option label="A级" value="A" />
            <el-option label="B级" value="B" />
            <el-option label="C级" value="C" />
            <el-option label="D级" value="D" />
          </el-select>
          <el-select
            v-else-if="filterForm.field === 'channelId'"
            v-model="filterForm.value"
            placeholder="请选择来源渠道"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="channel in channelOptions"
              :key="channel.id"
              :label="channel.channelName"
              :value="channel.id"
            />
          </el-select>
          <el-select
            v-else-if="filterForm.field === 'allocationStatus'"
            v-model="filterForm.value"
            placeholder="请选择分配状态"
            style="width: 100%"
          >
            <el-option label="未分配" value="unallocated" />
            <el-option label="已分配" value="allocated" />
          </el-select>
          <el-select
            v-else-if="filterForm.field === 'userId'"
            v-model="filterForm.value"
            placeholder="请选择负责人"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="user in userOptions"
              :key="user.id"
              :label="user.name"
              :value="user.id"
            />
          </el-select>
          <el-date-picker
            v-else-if="filterForm.field === 'createdTime'"
            v-model="filterForm.value"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showFilterDialog = false">取消</el-button>
        <el-button type="primary" @click="addFilter">添加</el-button>
      </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import {
  getCustomerList,
  createCustomer,
  updateCustomer,
  deleteCustomer,
  exportCustomers,
  importCustomers,
  batchDeleteCustomers,
  batchUpdateCustomerStatus,
  allocateCustomer,
  batchAllocateCustomers,
  transferCustomer,
  batchTransferCustomers,
  getUserList,
  getChannelOptions
} from '@/api/crm'

const router = useRouter()

// 表格数据
const loading = ref(false)
const tableData = ref([])
const selectedRows = ref([])

// 搜索表单
const searchForm = reactive({
  customerName: '',
  phone: '',
  customerStatus: '',
  intentionLevel: '',
  customerSource: '',
  channelId: '',
  allocationStatus: '',
  userId: '',
  dateRange: []
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 下拉选项
const userOptions = ref([])
const channelOptions = ref([])

// 加载状态管理
const submitLoading = ref(false)
const batchDeleteLoading = ref(false)
const batchStatusLoading = ref(false)
const batchAllocateLoading = ref(false)
const batchTransferLoading = ref(false)
const allocateLoading = ref(false)
const transferLoading = ref(false)

// 表格高度计算
const tableHeight = computed(() => {
  const windowHeight = window.innerHeight
  return windowHeight - 350
})

// 表单引用
const customerFormRef = ref<FormInstance>()
const allocateFormRef = ref<FormInstance>()
const batchAllocateFormRef = ref<FormInstance>()
const transferFormRef = ref<FormInstance>()
const batchTransferFormRef = ref<FormInstance>()

// 对话框状态
const detailDialog = reactive({
  visible: false,
  data: {}
})

const formDialog = reactive({
  visible: false,
  title: '新增客户',
  form: {
    customerName: '',
    phone: '',
    customerStatus: 'potential',
    intentionLevel: '',
    customerSource: '',
    loanAmount: 0,
    remark: ''
  }
})

const allocateDialog = reactive({
  visible: false,
  customerId: null,
  form: {
    userId: '',
    remark: ''
  }
})

const batchAllocateDialog = reactive({
  visible: false,
  form: {
    userId: '',
    remark: ''
  }
})

const transferDialog = reactive({
  visible: false,
  customerId: null,
  form: {
    userId: '',
    remark: ''
  }
})

const batchTransferDialog = reactive({
  visible: false,
  form: {
    userId: '',
    remark: ''
  }
})

// 表单验证规则
const formRules: FormRules = {
  customerName: [
    { required: true, message: '请输入客户姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '客户姓名长度为2-20个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { 
      pattern: /^1[3-9]\d{9}$/, 
      message: '请输入有效的手机号码', 
      trigger: 'blur' 
    }
  ],
  customerStatus: [{ required: true, message: '请选择客户状态', trigger: 'change' }],
  intentionLevel: [{ required: true, message: '请选择意向等级', trigger: 'change' }],
  customerSource: [{ required: true, message: '请选择客户来源', trigger: 'change' }],
  loanAmount: [
    { required: true, message: '请输入贷款金额', trigger: 'blur' },
    { type: 'number', min: 0, message: '贷款金额不能小于0', trigger: 'blur' }
  ],
  remark: [{ max: 500, message: '备注长度不能超过500个字符', trigger: 'blur' }]
}

const allocateRules: FormRules = {
  userId: [{ required: true, message: '请选择目标用户', trigger: 'change' }]
}

const batchAllocateRules: FormRules = {
  userId: [{ required: true, message: '请选择目标用户', trigger: 'change' }]
}

const transferRules: FormRules = {
  userId: [{ required: true, message: '请选择目标用户', trigger: 'change' }]
}

const batchTransferRules: FormRules = {
  userId: [{ required: true, message: '请选择目标用户', trigger: 'change' }]
}

// 获取客户状态标签
const getCustomerStatusLabel = (status: string) => {
  const labels: Record<string, string> = {
    potential: '潜在客户',
    intention: '意向客户',
    deal: '成交客户',
    invalid: '失效客户'
  }
  return labels[status] || status
}

// 获取客户状态类型
const getCustomerStatusType = (status: string) => {
  const types: Record<string, string> = {
    potential: 'info',
    intention: 'warning',
    deal: 'success',
    invalid: 'danger'
  }
  return types[status] || 'info'
}

// 获取客户来源标签
const getCustomerSourceLabel = (source: string) => {
  const labels: Record<string, string> = {
    online: '线上推广',
    offline: '线下推广',
    referral: '转介绍',
    organic: '自然流量'
  }
  return labels[source] || source
}

// 获取意向等级标签
const getIntentionLevelLabel = (level: string) => {
  const labels: Record<string, string> = {
    A: 'A级',
    B: 'B级',
    C: 'C级',
    D: 'D级'
  }
  return labels[level] || level
}

// 获取意向等级类型
const getIntentionLevelType = (level: string) => {
  const types: Record<string, string> = {
    A: 'danger',
    B: 'warning',
    C: 'info',
    D: 'default'
  }
  return types[level] || 'default'
}

// 格式化货币
const formatCurrency = (amount: number) => {
  return `¥${amount.toLocaleString()}`
}

// 获取客户列表
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    const res = await getCustomerList(params)
    tableData.value = res.rows
    pagination.total = res.total
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '获取客户列表失败'
    ElMessage.error(errorMessage)
    console.error('获取客户列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取下拉选项
const fetchOptions = async () => {
  try {
    const [users, channels] = await Promise.all([
      getUserList(),
      getChannelOptions()
    ])
    userOptions.value = users
    channelOptions.value = channels
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '获取选项数据失败'
    ElMessage.error(errorMessage)
    console.error('获取选项数据失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    customerName: '',
    phone: '',
    customerStatus: '',
    intentionLevel: '',
    customerSource: '',
    channelId: '',
    allocationStatus: '',
    userId: '',
    dateRange: []
  })
  handleSearch()
}

// 分页
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  fetchData()
}

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  fetchData()
}

// 选择行
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows
}

// 查看详情
const handleView = (row: any) => {
  router.push(`/crm/customer/detail/${row.id}`)
}

// 新增
const handleAdd = () => {
  formDialog.title = '新增客户'
  formDialog.form = {
    customerName: '',
    phone: '',
    customerStatus: 'potential',
    customerSource: '',
    loanAmount: 0,
    remark: ''
  }
  formDialog.visible = true
}

// 编辑
const handleEdit = async (row: any) => {
  try {
    const res = await getCustomerList({ id: row.id })
    formDialog.title = '编辑客户'
    formDialog.form = { ...res.rows[0] }
    formDialog.visible = true
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '获取客户详情失败'
    ElMessage.error(errorMessage)
    console.error('获取客户详情失败:', error)
  }
}

// 跟进
const handleFollowUp = (row: any) => {
  router.push(`/crm/follow-up?customerId=${row.id}`)
}

// 分配
const handleAllocate = (row: any) => {
  allocateDialog.customerId = row.id
  allocateDialog.form.userId = ''
  allocateDialog.form.remark = ''
  allocateDialog.visible = true
}

// 提交分配
const handleAllocateSubmit = async () => {
  if (!allocateFormRef.value || !allocateDialog.customerId) return
  
  await allocateFormRef.value.validate(async (valid) => {
    if (valid) {
      allocateLoading.value = true
      try {
        await allocateCustomer(allocateDialog.customerId, allocateDialog.form)
        ElMessage.success('客户分配成功')
        allocateDialog.visible = false
        fetchData()
      } catch (error: any) {
        const errorMessage = error?.response?.data?.message || error?.message || '客户分配失败'
        ElMessage.error(errorMessage)
        console.error('客户分配失败:', error)
      } finally {
        allocateLoading.value = false
      }
    }
  })
}

// 批量分配
const handleBatchAllocate = () => {
  if (selectedRows.value.length === 0) return
  batchAllocateDialog.form.userId = ''
  batchAllocateDialog.form.remark = ''
  batchAllocateDialog.visible = true
}

// 提交批量分配
const handleBatchAllocateSubmit = async () => {
  if (!batchAllocateFormRef.value) return
  
  await batchAllocateFormRef.value.validate(async (valid) => {
    if (valid) {
      batchAllocateLoading.value = true
      try {
        const customerIds = selectedRows.value.map(row => row.id)
        await batchAllocateCustomers(customerIds, batchAllocateDialog.form)
        ElMessage.success('批量分配成功')
        batchAllocateDialog.visible = false
        fetchData()
      } catch (error: any) {
        const errorMessage = error?.response?.data?.message || error?.message || '批量分配失败'
        ElMessage.error(errorMessage)
        console.error('批量分配失败:', error)
      } finally {
        batchAllocateLoading.value = false
      }
    }
  })
}

// 转移
const handleTransfer = (row: any) => {
  transferDialog.customerId = row.id
  transferDialog.form.userId = ''
  transferDialog.form.remark = ''
  transferDialog.visible = true
}

// 提交转移
const handleTransferSubmit = async () => {
  if (!transferFormRef.value || !transferDialog.customerId) return
  
  await transferFormRef.value.validate(async (valid) => {
    if (valid) {
      transferLoading.value = true
      try {
        await transferCustomer(transferDialog.customerId, transferDialog.form)
        ElMessage.success('客户转移成功')
        transferDialog.visible = false
        fetchData()
      } catch (error: any) {
        const errorMessage = error?.response?.data?.message || error?.message || '客户转移失败'
        ElMessage.error(errorMessage)
        console.error('客户转移失败:', error)
      } finally {
        transferLoading.value = false
      }
    }
  })
}

// 批量转移
const handleBatchTransfer = () => {
  if (selectedRows.value.length === 0) return
  batchTransferDialog.form.userId = ''
  batchTransferDialog.form.remark = ''
  batchTransferDialog.visible = true
}

// 提交批量转移
const handleBatchTransferSubmit = async () => {
  if (!batchTransferFormRef.value) return
  
  await batchTransferFormRef.value.validate(async (valid) => {
    if (valid) {
      batchTransferLoading.value = true
      try {
        const customerIds = selectedRows.value.map(row => row.id)
        await batchTransferCustomers(customerIds, batchTransferDialog.form)
        ElMessage.success('批量转移成功')
        batchTransferDialog.visible = false
        fetchData()
      } catch (error: any) {
        const errorMessage = error?.response?.data?.message || error?.message || '批量转移失败'
        ElMessage.error(errorMessage)
        console.error('批量转移失败:', error)
      } finally {
        batchTransferLoading.value = false
      }
    }
  })
}

// 更多操作
const handleMoreAction = async (command: string, row: any) => {
  switch (command) {
    case 'transfer':
      handleTransfer(row)
      break
    case 'invalid':
      try {
        await ElMessageBox.confirm('确定要标记该客户为失效吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await batchUpdateCustomerStatus([row.id], { status: 'invalid' })
        ElMessage.success('标记失效成功')
        fetchData()
      } catch (error: any) {
        if (error !== 'cancel') {
          const errorMessage = error?.response?.data?.message || error?.message || '标记失效失败'
          ElMessage.error(errorMessage)
          console.error('标记失效失败:', error)
        }
      }
      break
    case 'delete':
      try {
        await ElMessageBox.confirm('确定要删除该客户吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await deleteCustomer(row.id)
        ElMessage.success('删除客户成功')
        fetchData()
      } catch (error: any) {
        if (error !== 'cancel') {
          const errorMessage = error?.response?.data?.message || error?.message || '删除失败'
          ElMessage.error(errorMessage)
          console.error('删除失败:', error)
        }
      }
      break
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) return
  
  batchDeleteLoading.value = true
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个客户吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const ids = selectedRows.value.map(row => row.id)
    await batchDeleteCustomers(ids)
    ElMessage.success('批量删除成功')
    fetchData()
  } catch (error: any) {
    if (error !== 'cancel') {
      const errorMessage = error?.response?.data?.message || error?.message || '批量删除失败'
      ElMessage.error(errorMessage)
      console.error('批量删除失败:', error)
    }
  } finally {
    batchDeleteLoading.value = false
  }
}

// 批量标记失效
const handleBatchInvalid = async () => {
  if (selectedRows.value.length === 0) return
  
  try {
    await ElMessageBox.confirm(`确定要标记选中的 ${selectedRows.value.length} 个客户为失效吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    batchStatusLoading.value = true
    const customerIds = selectedRows.value.map(row => row.id)
    await batchUpdateCustomerStatus(customerIds, { status: 'invalid' })
    ElMessage.success('批量标记失效成功')
    fetchData()
  } catch (error: any) {
    if (error !== 'cancel') {
      const errorMessage = error?.response?.data?.message || error?.message || '批量标记失效失败'
      ElMessage.error(errorMessage)
      console.error('批量标记失效失败:', error)
    }
  } finally {
    batchStatusLoading.value = false
  }
}

// 批量状态更新
const handleBatchStatus = async (status: string) => {
  if (selectedRows.value.length === 0) return
  
  batchStatusLoading.value = true
  try {
    const action = status === 'invalid' ? '标记失效' : '更新状态'
    await ElMessageBox.confirm(`确定要${action}选中的 ${selectedRows.value.length} 个客户吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const ids = selectedRows.value.map(row => row.id)
    await batchUpdateCustomerStatus(ids, { status })
    ElMessage.success(`${action}成功`)
    fetchData()
  } catch (error: any) {
    if (error !== 'cancel') {
      const errorMessage = error?.response?.data?.message || error?.message || '批量操作失败'
      ElMessage.error(errorMessage)
      console.error('批量操作失败:', error)
    }
  } finally {
    batchStatusLoading.value = false
  }
}

// 批量更新客户状态（带备注）
const handleBatchUpdateStatus = async (status: string, remark?: string) => {
  if (selectedRows.value.length === 0) return
  
  batchStatusLoading.value = true
  try {
    const action = status === 'invalid' ? '标记失效' : '更新状态'
    await ElMessageBox.confirm(`确定要${action}选中的 ${selectedRows.value.length} 个客户吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const ids = selectedRows.value.map(row => row.id)
    await batchUpdateCustomerStatus(ids, { status, remark })
    ElMessage.success(`${action}成功`)
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量操作失败')
    }
  } finally {
    batchStatusLoading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!customerFormRef.value) return
  
  await customerFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (formDialog.title === '新增客户') {
          await createCustomer(formDialog.form)
          ElMessage.success('新增客户成功')
        } else {
          await updateCustomer(formDialog.form.id, formDialog.form)
          ElMessage.success('更新客户成功')
        }
        formDialog.visible = false
        fetchData()
      } catch (error: any) {
        const errorMessage = error?.response?.data?.message || error?.message || '操作失败'
        ElMessage.error(errorMessage)
        console.error('提交表单失败:', error)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 导出
const handleExport = async () => {
  try {
    const exportLoading = ElLoading.service({
      lock: true,
      text: '正在导出数据...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    
    const blob = await exportCustomers(searchForm)
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `客户_${new Date().toLocaleDateString()}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
    
    exportLoading.close()
    ElMessage.success('导出成功')
  } catch (error: any) {
    const errorMessage = error?.response?.data?.message || error?.message || '导出失败'
    ElMessage.error(errorMessage)
    console.error('导出失败:', error)
  }
}

// 导入
const handleImport = async (options: any) => {
  const file = options.file
  const formData = new FormData()
  formData.append('file', file)
  
  const importLoading = ElLoading.service({
    lock: true,
    text: '正在导入数据...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  try {
    await importCustomers(formData)
    importLoading.close()
    ElMessage.success('导入成功')
    fetchData()
  } catch (error: any) {
    importLoading.close()
    const errorMessage = error?.response?.data?.message || error?.message || '导入失败'
    ElMessage.error(errorMessage)
    console.error('导入失败:', error)
  }
}

// 初始化
onMounted(() => {
  fetchData()
  fetchOptions()
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    // 表格高度会自动重新计算
  })
})
</script>

<style scoped lang="scss">
.customer-management {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
  }

  .header-actions {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
  }

  .search-form {
    margin-bottom: 20px;
  }

  .batch-actions {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  // 响应式设计
  @media screen and (max-width: 768px) {
    .card-header {
      flex-direction: column;
      align-items: flex-start;
    }

    .header-actions {
      width: 100%;
      justify-content: flex-end;
    }

    .batch-actions {
      justify-content: center;
    }

    .pagination {
      justify-content: center;
    }
  }

  @media screen and (max-width: 480px) {
    .search-form {
      .el-form-item {
        margin-bottom: 10px;
      }
    }

    .batch-actions {
      .el-button {
        margin-bottom: 5px;
      }
    }
  }
}

// 全局响应式样式
.responsive-table {
  :deep(.el-table__header) {
    th {
      background-color: #f5f7fa;
      font-weight: 600;
    }
  }
}

.responsive-pagination {
  :deep(.el-pagination__sizes) {
    @media screen and (max-width: 768px) {
      display: none;
    }
  }
}

.responsive-dialog {
  @media screen and (max-width: 768px) {
    :deep(.el-dialog) {
      width: 95% !important;
      margin-top: 10vh !important;
    }
  }
}
</style>

// 导出配置
// 导出配置
// 导出配置
// 导出配置相关函数
// 导出配置
// 导出配置
const exportDialog = reactive({
  visible: false,
  selectAll: false,
  selectedFields: ['customerName', 'phone', 'customerStatus', 'intentionLevel', 'channelName', 'allocationStatus', 'ownerUserName', 'createdTime'],
  availableFields: [
    { key: 'customerName', label: '客户名称' },
    { key: 'phone', label: '手机号' },
    { key: 'customerStatus', label: '客户状态' },
    { key: 'intentionLevel', label: '意向等级' },
    { key: 'channelName', label: '来源渠道' },
    { key: 'allocationStatus', label: '分配状态' },
    { key: 'ownerUserName', label: '负责人' },
    { key: 'lastFollowUpTime', label: '最后跟进时间' },
    { key: 'createdTime', label: '创建时间' },
    { key: 'loanAmount', label: '贷款金额' },
    { key: 'followUpCount', label: '跟进次数' },
    { key: 'nextFollowUpTime', label: '下次跟进时间' },
    { key: 'remark', label: '备注' }
  ],
  filters: {},
  format: 'excel'
})

const showFilterDialog = ref(false)
const filterForm = reactive({
  field: '',
  value: ''
})

const exportLoading = ref(false)
</template>